package com.zrkizzy.system.api.core;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zrkizzy.common.core.domain.response.OptionsVO;
import com.zrkizzy.common.core.domain.response.PageResult;
import com.zrkizzy.common.core.domain.response.Result;
import com.zrkizzy.common.core.utils.bean.BeanCopyUtil;
import com.zrkizzy.common.models.domain.system.core.Role;
import com.zrkizzy.common.models.dto.system.core.RoleDTO;
import com.zrkizzy.common.models.query.system.core.RoleQuery;
import com.zrkizzy.common.models.vo.system.core.RoleVO;
import com.zrkizzy.module.security.constant.SecurityConst;
import com.zrkizzy.module.system.exception.SystemErrorCode;
import com.zrkizzy.system.facade.service.core.IRoleService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 角色管理控制器
 *
 * @author zhangrongkang
 * @since 2023/3/8
 */
@Tag(name = "角色管理控制器")
@RestController
@RequestMapping("/admin/role")
public class RoleController {

    @Autowired
    private IRoleService roleService;

    @Operation(summary = "获取所有角色")
    @PostMapping("/list")
    public Result<PageResult<RoleVO>> listRoles(@RequestBody RoleQuery roleQuery) {
        // 查询到对应的角色集合
        Page<Role> rolePage = roleService.listRoles(roleQuery);
        // 处理对应数据集合并返回数据
        return Result.ok(PageResult.<RoleVO>builder().total(rolePage.getTotal())
                // 角色集合
                .list(BeanCopyUtil.copyList(rolePage.getRecords(), RoleVO.class)).build());
    }

    @Operation(summary = "添加-更新角色")
    @PostMapping("/save")
    public Result<Boolean> saveRole(@RequestBody RoleDTO roleDTO) {
        // 检查操作的角色是否为系统最高权限角色
        if (roleDTO.getMark().equals(SecurityConst.ADMIN)) {
            return Result.failure(SystemErrorCode.SUPER_ADMIN_DATA_UNABLE_OPERATE);
        }
        return Result.ok(roleService.saveRole(roleDTO));
    }

    @Operation(summary = "获取指定角色信息")
    @GetMapping("/getRoleById/{roleId}")
    public Result<RoleVO> getRoleById (@PathVariable Long roleId) {
        return Result.ok(BeanCopyUtil.copy(roleService.getRoleById(roleId), RoleVO.class));
    }

    @Operation(summary = "批量删除角色数据")
    @DeleteMapping("/delete")
    public Result<Boolean> delete(@RequestBody List<Long> ids) {
        return Result.ok(roleService.deleteBatch(ids));
    }

    @Operation(summary = "获取角色选项")
    @GetMapping("/listRoleOptions")
    public Result<List<OptionsVO>> listRoleOptions() {
        return Result.ok(roleService.listRoleOptions());
    }

}
